package com.sky.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.exception.BusinessException;
import com.sky.properties.BaiduMapProperties;
import com.sky.result.Location;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.util.HashMap;
import java.util.Map;

@Data
@AllArgsConstructor
public class BaiduMapUtil {

    private BaiduMapProperties baiduMapProperties;

    /**
     * 获取位置对应的坐标(经纬度)
     */
    public Location getAddressGeo(String address){
        //发送http请求, 获取位置对应的坐标
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("address", address);
        paramMap.put("output", "json");
        paramMap.put("ak", baiduMapProperties.getAk());

        String result = HttpClientUtil.doGet(baiduMapProperties.getGeoCoderUrl(), paramMap);
        System.out.println(result);

        JSONObject jsonObject = JSON.parseObject(result);
        Integer status = jsonObject.getInteger("status");
        if (status != 0){
            throw new BusinessException(MessageConstant.ADDRESS_PARSE_ERROR);
        }

        String lat = jsonObject.getJSONObject("result").getJSONObject("location").getString("lat");
        String lng = jsonObject.getJSONObject("result").getJSONObject("location").getString("lng");

        return new Location(lat, lng);
    }


    /**
     * 获取两个坐标之间的路线距离
     */
    public Integer getDistance(Location origin , Location destination){
        //发送http请求, 获取位置对应的坐标
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("ak", baiduMapProperties.getAk());
        paramMap.put("origin", origin.getLatLng());
        paramMap.put("destination", destination.getLatLng());

        String result = HttpClientUtil.doGet(baiduMapProperties.getDrivingUrl(), paramMap);

        JSONObject jsonObject = JSON.parseObject(result);
        Integer status = jsonObject.getInteger("status");
        if (status != 0){
            throw new BusinessException(MessageConstant.ADDRESS_PARSE_ERROR);
        }

        JSONObject routeObject = (JSONObject) jsonObject.getJSONObject("result").getJSONArray("routes").get(0);
        Integer distance = routeObject.getInteger("distance");

        return distance;
    }

}
